package com.rop.system.aspect;

import com.alibaba.fastjson.JSON;
import com.rop.model.system.SysOperLog;
import com.rop.system.service.AsyncOperationLogService;
import com.rop.system.annotation.SysLog;
import com.rop.util.IpUtil;
import com.rop.util.JwtHelper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.BindException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;


/**
 * @Title: LogAspect
 * @Author Rop
 * @Date 2023/5/15 20:59
 * @description: 操作日志记录处理
 */

@Aspect
@Component
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 微服务切换为feign调用接口
    @Resource
    private AsyncOperationLogService asyncOperationLogService;

    /**
     * 处理完请求后执行
     *
     * @param joinPoint     切点
     * @param controllerLog ""
     * @param jsonResult    ""
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, SysLog controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint     "切点"
     * @param controllerLog ""
     * @param e             ""
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, SysLog controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, SysLog controllerLog, final Exception e, Object jsonResult) {
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();

            // ==== 数据库日志 ====
            SysOperLog sysOperLog = new SysOperLog();
            sysOperLog.setStatus(1);

            // 请求的地址
            String ip = IpUtil.getIpAddress(request);
            sysOperLog.setOperIp(ip);
            sysOperLog.setOperUrl(request.getRequestURI());

            String token = request.getHeader("token");
            String username = JwtHelper.getUsername(token);
            sysOperLog.setOperName(username);

            if (Objects.nonNull(e)) {
                sysOperLog.setStatus(0);
                sysOperLog.setErrorMsg(e.getMessage());
            }

            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysOperLog.setMethod(className + "." + methodName + "()");

            // 设置请求方式
            sysOperLog.setRequestMethod(request.getMethod());

            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, sysOperLog, jsonResult);

            // 保存数据库
            asyncOperationLogService.saveLog(sysOperLog);
        } catch (Exception ex) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param controllerLog 日志
     * @param sysOperLog    操作日志
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, SysLog controllerLog, SysOperLog sysOperLog, Object jsonResult) {
        // 设置action动作
        sysOperLog.setBusinessType(controllerLog.businessType().name());

        // 设置标题
        sysOperLog.setTitle(controllerLog.title());

        // 设置操作人类别
        sysOperLog.setOperatorType(controllerLog.OperatorType().name());

        // 是否需要保存request，参数和值
        if (controllerLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中
            setRequestValue(joinPoint, sysOperLog);
        }

        // 是否需要保存response，参数和值
        if (controllerLog.isSaveResponseData() && jsonResult != null) {
            sysOperLog.setJsonResult(JSON.toJSONString(jsonResult));
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param sysOperLog 操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog sysOperLog) {
        String requestMethod = sysOperLog.getRequestMethod();
        if (Objects.equals(HttpMethod.PUT.name(), sysOperLog.getRequestMethod())) {
            String params = argsArrayToString(joinPoint.getArgs());
            sysOperLog.setOperParam(params);
        }
    }

    private String argsArrayToString(Object[] args) {
        StringBuilder params = new StringBuilder();
        if (Objects.nonNull(args)) {
            for (Object arg : args) {
                if (StringUtils.isNotBlank((CharSequence) arg) && !isFilterObject(arg)) {
                    try {
                        Object jsonObj = JSON.toJSON(arg);
                        params.append(jsonObj.toString());
                    } catch (Exception ignored) {
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象
     * @param o 对象信息
     * @return 如果是需要过滤的对象，则返回true，否则返回false
     */
    @SuppressWarnings("rawTypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();

        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile
                || o instanceof HttpServletRequest
                || o instanceof HttpServletResponse
                || o instanceof BindException;
    }
}
